package com.woniuxy.util;


import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;


public class CommonsUtil {


    public Boolean sendEmail(String title, String content, String recipient, EmailSource emailSource) {
        //1.创建邮件
        // Properties用于设置发送邮件的线管环境配置
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", "SMTP");
        properties.setProperty("mail.host", "smtp.163.com");
        properties.setProperty("mail.smtp.auth", "true");

        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailSource.getUsername(), emailSource.getPassword());
            }
        };
        Session session = Session.getInstance(properties, authenticator);

        MimeMessage message = new MimeMessage(session);

        try {
            //2.设置邮件相关属性
            message.setFrom(new InternetAddress(emailSource.getUsername()));//设置邮件发送者
            //设置邮件标题
            message.setSubject(title);//设置邮件的标题
            //邮件的内容
            message.setContent(content, "text/html;charset=utf-8");
            //邮件接收者
            message.setRecipients(Message.RecipientType.TO, new InternetAddress(recipient).toString());
            //3、发送邮件
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 获取随机验证码
     *
     * @param length
     * @return
     */
    public  String getRandomString(int length) {
        String originString = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789";
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            builder.append(originString.charAt(new Random().nextInt(originString.length())));
        }
        return String.valueOf(builder);
    }
}
